C++ Basics

While structure

The while structure executes the statements between the braces while a condition is true. In this case we do not know how many times the code will be executed (unlike the for structure where we know from the beginning how many steps will take to execute the code).

General syntax:

while(a condition is true)
{
    Execute all statements inside the braces
}

Practical example (console menu):

#include <iostream>
int main()
{
    int option = 0;
    while(option != 5)
    {
        std::cout << "1. First menu option" << std::endl;
        std::cout << "2. Second menu option" << std::endl;
        std::cout << "3. Third menu option" << std::endl;
        std::cout << "4. Fourth menu option" << std::endl;
        std::cout << "5. Exit" << std::endl;
        std::cout << "Please enter an option: ";
        std::cin >> option;
    }
}

In the code above, if the option variable had the value 5 from the start, the while statement is true and the menu would not be displayed not even once.